package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.dao.ToolsControlWayDao;
import com.sugon.dao.ToolsListDao;
import com.sugon.dao.ToolsTypeDao;
import com.sugon.entity.*;
import com.sugon.modules.base.model.vo.ProcessProgressConst;
import com.sugon.service.*;
import com.sugon.utils.ProcessInfoEnum;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 工装清单管理Service实现类
 *
 * @author sugon
 * @date 2019-08-01 16:42:44
 */
@Service("toolsListService")
public class ToolsListServiceImpl implements ToolsListService {

    @Autowired
    private ToolsListDao toolsListDao;
    @Autowired
    private ToolsTypeDao toolsTypeDao;
    @Autowired
    private ToolsControlWayDao toolsControlWayDao;
    @Autowired
    private SysProcessInfoService sysProcessInfoService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysMsgService sysmsgService;
    @Autowired
    private ToolsBaseService toolsBaseService;

    @Override
    public ToolsListEntity queryByCode(String toolsCode) {
        return toolsListDao.loadByCode(toolsCode);
    }

    @Override
    public ToolsListEntity queryObject(String id) {
        return toolsListDao.queryObject(id);
    }

    @Override
    public List<ToolsListEntity> queryList(Map<String, Object> map) {
        return toolsListDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return toolsListDao.queryTotal(map);
    }

    @Override
    public int save(ToolsListEntity toolslist) {
        toolslist.setId(RandomUtil.randomString(32));
        toolslist.setToolsCode(generateUniqueCode());
        toolslist.setWorkshop(StrUtil.sub(toolslist.getProductLine(), 0, 4));
        toolslist.setCreateTime(DateUtil.date());
        toolslist.setCreateUser(ShiroUtils.getUserId());
        toolslist.setUpdateUser(toolslist.getCreateUser());
        toolslist.setUpdateTime(toolslist.getCreateTime());
        toolslist.setProgress(ProcessProgressConst.CJ_PE_APPROVING);
        toolslist.setStockNum(0);
        toolslist.setScrapNum(0);
        toolslist.setTransitNum(0);
        sysProcessInfoService.saveProcessInfo(toolslist.getId(), ProcessInfoEnum.TLS_GZML, 0, null);
        int rows = toolsListDao.save(toolslist);
        if (rows > 0) {
            SysMsgEntity msgEntity = new SysMsgEntity();
            String Id = toolslist.getId();
            msgEntity.setDataId(Id);
            msgEntity.setDataUrl("../tools/toolslist.html?Id=" + Id);
            sysmsgService.addApproveItem(ProcessInfoEnum.TLS_GZML, msgEntity, 0);
        }
        return rows;
    }

    @Override
    public int update(ToolsListEntity toolslist) {
        toolslist.setUpdateTime(DateUtil.date());
        toolslist.setUpdateUser(ShiroUtils.getUserId());
        // 设置车间ID
        toolslist.setWorkshop(StrUtil.sub(toolslist.getProductLine(), 0, 4));

//        if (toolslist.getReviewStatus() != 0) {
//            sysProcessInfoService.saveProcessInfo(toolslist.getId(), ProcessInfoEnum.TLS_GZML, 0, null);
//        }
//        //修改内容后，需重新进行审批
//        toolslist.setReviewStatus(0);
        int rows = toolsListDao.update(toolslist);
        if (rows > 0) {
            SysMsgEntity msgEntity = new SysMsgEntity();
            String Id = toolslist.getId();
            msgEntity.setDataId(Id);
            msgEntity.setDataUrl("../tools/toolslist.html?Id=" + Id);
            sysmsgService.addApproveItem(ProcessInfoEnum.TLS_GZML, msgEntity, 0);
        }
        return rows;
    }

    @Override
    public int delete(String id) {
        return toolsListDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return toolsListDao.deleteBatch(ids);
    }

    @Override
    public int importE(MultipartFile file) {
        List<String[]> list = ExcelImport.getExcelData(file);
        int count = 0;
        // 每行导入的内容应该包含的列数
        int cols = 13;
        if (CollectionUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                ToolsListEntity toolslistEntity = null;
                int size = i + 1;
                if (size < list.size()) {
                    String[] array = list.get(size);
                    if (ArrayUtil.isNotEmpty(array) && array.length < cols) {
                        array = ArrayUtil.resize(array, cols);
                    }
                    // 如果工装编码已填写则更新，否则新增
                    if (StrUtil.isNotEmpty(array[1])) {
                        toolslistEntity = toolsListDao.loadByCode(array[1]);
                    }
                    if (toolslistEntity == null) {
                        toolslistEntity = new ToolsListEntity();
                        /*
                            依次根据图号、自制图号、型号规格获取工装档案
                         */
                        ToolsBaseEntity toolsBase = toolsBaseService.queryList(array[2], array[3], array[4]);
                        if (toolsBase == null) {
                            continue;
                        }
                        toolslistEntity.setToolsBaseId(toolsBase.getId());
                    }
                    toolslistEntity.setCapacity(array[6]);
                    // 设置产线
                    SysDeptEntity line = sysDeptService.getByDCode(array[7]);
                    if (line != null) {
                        toolslistEntity.setProductLine(line.getDeptId());
                    }
                    // 设置工序
                    toolslistEntity.setUseProcedure(array[8]);
                    // 设置管控方式：管控方式统一在工装档案中管理
                    //if (StrUtil.isNotEmpty(array[11])) {
                    //    String controlCode = "";
                    //    String[] controlNames = array[11].split(",");
                    //    for (String controlName : controlNames) {
                    //        ToolsControlWayEntity toolsControlWay = getByControlName(controlName);
                    //        if (toolsControlWay != null) {
                    //            controlCode += "," + toolsControlWay.getControlCode();
                    //        }
                    //    }
                    //    toolslistEntity.setControlWay(controlCode.replaceFirst(",", ""));
                    //} else {
                    //    toolslistEntity.setControlWay("");
                    //}
                    // 设置备注
                    toolslistEntity.setRemark(array[12]);
                    if (StrUtil.isNotEmpty(toolslistEntity.getId())) {
                        count += update(toolslistEntity);
                    } else {
                        count += save(toolslistEntity);
                    }
                }
            }
        }
        return count;
    }

    @Override
    public String generateUniqueCode() {
        String lastestToolsCode = toolsListDao.getLastestToolsCode();
        int num = 1;
        if (StrUtil.isNotEmpty(lastestToolsCode)) {
            num += Integer.parseInt(lastestToolsCode.replace(ErmsCodePrefix.TOOLS_CODE_PREFIX, ""));
        }
        return ErmsCodePrefix.TOOLS_CODE_PREFIX + String.format("%04d", num);
    }

    /**
     * 根据类别名称获取工装类别
     *
     * @param typeName
     * @return
     */
    private ToolsTypeEntity getByTypeName(String typeName) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("typeName", typeName);
        List<ToolsTypeEntity> toolsTypes = toolsTypeDao.queryList(param);
        return CollectionUtil.isNotEmpty(toolsTypes) ? toolsTypes.get(0) : null;
    }

    private ToolsControlWayEntity getByControlName(String controlName) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("name", controlName);
        List<ToolsControlWayEntity> toolsTypes = toolsControlWayDao.queryList(param);
        return CollectionUtil.isNotEmpty(toolsTypes) ? toolsTypes.get(0) : null;
    }

}
